{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bbf2d497",
   "metadata": {},
   "source": [
    "## 过滤和修剪消息\n",
    "\n",
    "### 回顾\n",
    "现在，我们对一些事情有了更深入的了解：<br/>\n",
    "\n",
    "- 如何自定义图形状态模式\n",
    "- 如何定义自定义状态reducer\n",
    "- 如何使用多个图形状态模式 \n",
    "\n",
    "### 目标\n",
    "\n",
    "本期我们讨论一下在图形状态下处理消息的高级方法。<br/>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0001781d",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install --quiet -U langchain_core langgraph langchain_openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "15d07f5e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OPENAI_API_KEY: ········\n",
      "OPENAI_BASE_URL: ········\n"
     ]
    }
   ],
   "source": [
    "import os, getpass\n",
    "\n",
    "\n",
    "def _set_env(var: str):\n",
    "    if not os.environ.get(var):\n",
    "        os.environ[var] = getpass.getpass(f\"{var}: \")\n",
    "\n",
    "_set_env(\"OPENAI_API_KEY\")\n",
    "_set_env(\"OPENAI_BASE_URL\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0bbe3daa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Name: Ronnie\n",
      "\n",
      "所以你说你在研究神经网络？\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Simon\n",
      "\n",
      "是的，我知道神经网络。但我还应该了解哪些其他东西呢？\n"
     ]
    }
   ],
   "source": [
    "from pprint import pprint\n",
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "messages = [AIMessage(f\"所以你说你在研究神经网络？\", name=\"Ronnie\")]\n",
    "messages.append(HumanMessage(f\"是的，我知道神经网络。但我还应该了解哪些其他东西呢？\", name=\"Simon\"))\n",
    "\n",
    "for m in messages:\n",
    "    m.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "64c13688",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='除了神经网络，以下是一些在机器学习和数据科学领域中你可能也会感兴趣的主题：\\n\\n1. **监督学习**：了解各种监督学习算法，例如决策树、支持向量机和k-近邻算法。\\n\\n2. **无监督学习**：研究无监督学习的技术，如聚类（例如K均值算法）、降维（例如PCA和t-SNE）。\\n\\n3. **半监督学习**：结合了少量标签数据和大量无标签数据进行训练的方法。\\n\\n4. **强化学习**：这是一种通过与环境交互来学习策略的技术，适用场合包括游戏AI和自动驾驶。\\n\\n5. **深度学习架构**：除了常用的前馈神经网络（如CNN用于图像处理和RNN用于序列数据）之外，还有GANs（生成对抗网络）和transformers（如用于自然语言处理的BERT和GPT）。\\n\\n6. **特征工程**：学习如何选择、提取和变换数据特征以优化模型性能。\\n\\n7. **模型评估与选择**：掌握交叉验证、混淆矩阵、ROC曲线等模型评估方法，以及如何选用合适的性能指标。\\n\\n8. **大数据技术**：熟悉使用Hadoop、Spark等技术进行大规模数据处理。\\n\\n9. **数据清洗与处理**：学习处理和清洗原始数据，以确保数据质量。\\n\\n10. **道德与社会影响**：了解AI技术的伦理问题和社会影响，包括数据隐私、算法偏见等。\\n\\n11. **编程与工具**：熟练使用Python进行机器学习是非常有帮助的，相关的库包括NumPy、Pandas、scikit-learn、TensorFlow和PyTorch。\\n\\n12. **统计学与概率论**：掌握基本的统计学和概率知识以理解数据分析中的不确定性。\\n\\n多了解这些领域会帮助你更全面地理解和应用机器学习到实际问题中。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 434, 'prompt_tokens': 43, 'total_tokens': 477, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_ee1d74bde0', 'id': 'chatcmpl-BPQwGM9VUYgj9ME0An2iYOyyvE6Om', 'finish_reason': 'stop', 'logprobs': None}, id='run-1d8bddbf-0b89-4af4-89cb-aa078699ac51-0', usage_metadata={'input_tokens': 43, 'output_tokens': 434, 'total_tokens': 477, 'input_token_details': {}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-4o\",\n",
    "                timeout=60 )\n",
    "llm.invoke(messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f9194dfe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OPENAI_API_KEY 已设置: True\n"
     ]
    }
   ],
   "source": [
    "print(\"OPENAI_API_KEY 已设置:\", os.environ.get(\"OPENAI_API_KEY\") is not None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "84e95b98",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sk-9jGAgpYWFWdc8Ellt5KUUj5J1YZHWzuYKfe3XMpWa43tNLwf\n"
     ]
    }
   ],
   "source": [
    "print(os.environ[\"OPENAI_API_KEY\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "90415147",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='除了神经网络之外，您可以接触以下几个领域和概念，以拓宽您在机器学习和人工智能方面的知识：\\n\\n1. **深度学习**：了解卷积神经网络（CNN）、循环神经网络（RNN）、长期短期记忆网络（LSTM）等深度学习模型，及其在图像识别、序列预测等领域的应用。\\n\\n2. **监督学习和无监督学习**：监督学习涉及使用标记数据训练模型，而无监督学习则主要用于在未标记的数据集中寻找模式和关系。\\n\\n3. **强化学习**：这种学习方法通过奖惩机制训练代理，从而达到特定目标或完成特定任务，如AlphaGo达到卓越的围棋水平。\\n\\n4. **特征工程**：学习如何选择、转换、创建适合模型训练的数据特征，以提高模型的准确性和效率。\\n\\n5. **模型评估与选择**：理解交叉验证、混淆矩阵、ROC曲线等评估方法，帮助您选择最佳的机器学习模型。\\n\\n6. **大数据和数据处理**：熟悉处理和管理大规模数据集的工具和技术，如Hadoop、Spark等。\\n\\n7. **自然语言处理（NLP）**：如果您对语言数据感兴趣，可以学习NLP相关技术，包括文本分析、情感分析、计算语言生成等。\\n\\n8. **计算机视觉**：研究如何使计算机“看到”并理解图像和视频数据。\\n\\n9. **生成对抗网络（GAN）**：理解如何使用两部分模型（生成器和判别器）来生成新的、类似于真实数据的样本。\\n\\n10. **领域应用**：考虑机器学习在特定领域的应用，如金融、医疗、交通、游戏等，以深入了解其实际应用潜力。\\n\\n探索上述领域将帮助您全面理解机器学习和人工智能的广泛应用及其技术基础。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 420, 'prompt_tokens': 62, 'total_tokens': 482, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_ee1d74bde0', 'id': 'chatcmpl-BPgVObzDA1NhwPZkWwnsvonk2FFnF', 'finish_reason': 'stop', 'logprobs': None}, id='run-a45ddb07-fa65-471c-b6f9-da1d1e6e4b76-0', usage_metadata={'input_tokens': 62, 'output_tokens': 420, 'total_tokens': 482, 'input_token_details': {}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-4o\",\n",
    "                 openai_api_key= os.environ[\"OPENAI_API_KEY\"],\n",
    "                timeout=60 )\n",
    "llm.invoke(messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "76c4ffa7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAAN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WUDvmoyJ7D8nm91ULUAcmEPNJlvMwwep4BOGbTE2Bic+7jpjMOgAgPk/QTq7AgEgMR2vry1zVUU1didFEmXPtYXAMVwWQfR1SoEF9jU2ipH7gWyyS9e837vhPm6VSVXhod11zbc7R1Spl4F9e+bydXF0T0oUCyaHcz0YMnYthziMnv5LJaPSjWJos6ih/koWQ1SC+t7T8TiOIVpEsxy2jhs0Xi+R5J740GBvlMr/uXZ4Z/qdHtPdlUtX0l1ccOvL5+i2zfVTBI4Zknru81/UioRzMidlMzpAYMclyKBhH27SkLCYtjCdgQcAEteiqjWKBfdhUsgvqUfAu7fmMUldFYxvca9FrDH0HURDzQkEXN22EX/6iUr9IZVst1K++zqyuKXr4OI5jgCBgxL0NS948IJVQFtVz+tz21v271kAAItqorBbO3eWjcj+tQV9r9g/hUxIBRs2Y/q/nmotuOALj/dymGoyNKOp4+LjTaScAELhr5gMAVEo1DFPW5LVajVab+0aqxWqUiN373pWKQKSNn0jZlcqMeSEq//YaaY8JZXEV+9ZUSwKUUl+yLyhWUH9XG9uDn/w8Nc5Kyn5oExeEVt+qRx3euL0steiqDQolQZUAFMcXOWz4vrWaoC6BnbiN1FRpkMmcQ1+m0gdFpY9BIIInvhFSdqXK3GSlsFjvQVuu4wMbtQLQFfP7/RfVGOAFxPjCnWWM02qwG+sMEXH8tBHu2x1koCvu+sbZ5su5Wv8opU+ogqYBho7BZnJoy3UAQ58d5x/ehRYXLL1zQK4cayo4rxeIeRIficRXxBMgfCFCh6ObQjAn5rRjqAM3NZpNDRa/YEFSuiKut4y+K3bEPJzaCltZgbm+yqGrs1tNmF+oWFfnpRuoiGU8mwkVy5CgSLE6UhCdKFX4Uu8S/h0MrJXgsOFeuz4DgkA8QUeHzLJyvYpOhldXzU8InAbMw2nAPJwGzMNpwDycBszzHwXpYPeVoim9AAAAAElFTkSuQmCC",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "from langgraph.graph import MessagesState\n",
    "from langgraph.graph import StateGraph, START, END\n",
    "\n",
    "# LLM节点\n",
    "def chat_model_node(state: MessagesState):\n",
    "    return {\"messages\": llm.invoke(state[\"messages\"])}\n",
    "\n",
    "# 建立图\n",
    "builder = StateGraph(MessagesState)\n",
    "builder.add_node(\"chat_model\", chat_model_node)\n",
    "builder.add_edge(START, \"chat_model\")\n",
    "builder.add_edge(\"chat_model\", END)\n",
    "graph = builder.compile()\n",
    "\n",
    "display(Image(graph.get_graph().draw_mermaid_png()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e56b45e4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Name: Trump\n",
      "\n",
      "你好啊，我是特朗普\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Ronnie\n",
      "\n",
      "你好\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Name: Ronnie\n",
      "\n",
      "所以你说你在研究神经网络？\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Lance\n",
      "\n",
      "是的，我知道神经网络。但我还应该了解哪些其他东西呢？\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "了解神经网络是掌握机器学习和数据科学的一个重要部分，不过你还可以拓展一些其他相关领域的知识，以便更全面地理解和应用这些技术。这里有几个你可以考虑深入了解的领域和概念：\n",
      "\n",
      "1. **机器学习的基本概念**：\n",
      "   - 监督学习、无监督学习以及强化学习的区别。\n",
      "   - 常见算法，如线性回归、逻辑回归、支持向量机、决策树、随机森林等。\n",
      "\n",
      "2. **深度学习**：\n",
      "   - 深度学习是神经网络的一个分支，涉及更复杂的网络结构，如卷积神经网络（CNN）用于图像处理、循环神经网络（RNN）用于处理序列数据、以及长短时记忆网络（LSTM）和变压器模型在自然语言处理中的应用。\n",
      "\n",
      "3. **数据预处理和特征工程**：\n",
      "   - 在机器学习和深度学习中，对数据进行预处理和特征选择是至关重要的。包括数据清理、标准化、正则化等技术。\n",
      "\n",
      "4. **模型评估与优化**：\n",
      "   - 如何评估模型性能，包括使用准确率、精度、召回率、F1分数、ROC-AUC等指标。\n",
      "   - 模型优化技术，如超参数调整和模型调优。\n",
      "\n",
      "5. **概率与统计**：\n",
      "   - 理解概率论和统计学的基本原理，因为许多机器学习算法都是基于这些原理构建的。\n",
      "\n",
      "6. **编程和工具**：\n",
      "   - 深入学习Python编程语言，以及相关的库如NumPy、Pandas、Scikit-learn、TensorFlow和PyTorch等，它们是构建和训练神经网络的常用工具。\n",
      "\n",
      "7. **大数据技术**：\n",
      "   - 学习如何处理和分析大规模数据集，包括使用数据库技术、Hadoop、Spark等。\n",
      "\n",
      "8. **伦理和安全性**：\n",
      "   - 了解机器学习在应用中面临的伦理问题和数据安全性。\n",
      "\n",
      "通过掌握这些领域，你将为自己打下一个坚实的基础，不仅可以更好地理解神经网络，还能够应对机器学习中的复杂问题和应用场景。\n"
     ]
    }
   ],
   "source": [
    "# 带标记的消息列表\n",
    "messages = [AIMessage(\"你好啊，我是特朗普\", name=\"Trump\", id=\"1\")]\n",
    "messages.append(HumanMessage(\"你好\", name=\"Ronnie\", id=\"2\"))\n",
    "messages.append(AIMessage(\"所以你说你在研究神经网络？\", name=\"Ronnie\", id=\"3\"))\n",
    "messages.append(HumanMessage(\"是的，我知道神经网络。但我还应该了解哪些其他东西呢？\", name=\"Lance\", id=\"4\"))\n",
    "\n",
    "output = graph.invoke({'messages': messages})\n",
    "for m in output['messages']:\n",
    "    m.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "294f48ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "messages.append(output['messages'][-1])\n",
    "messages.append(HumanMessage(f\"告诉我更多关于神经网络的信息\", name=\"Ronnie\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "bb899160",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Name: Trump\n",
      "\n",
      "你好啊，我是特朗普\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Ronnie\n",
      "\n",
      "你好\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Name: Ronnie\n",
      "\n",
      "所以你说你在研究神经网络？\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Lance\n",
      "\n",
      "是的，我知道神经网络。但我还应该了解哪些其他东西呢？\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "了解神经网络是掌握机器学习和数据科学的一个重要部分，不过你还可以拓展一些其他相关领域的知识，以便更全面地理解和应用这些技术。这里有几个你可以考虑深入了解的领域和概念：\n",
      "\n",
      "1. **机器学习的基本概念**：\n",
      "   - 监督学习、无监督学习以及强化学习的区别。\n",
      "   - 常见算法，如线性回归、逻辑回归、支持向量机、决策树、随机森林等。\n",
      "\n",
      "2. **深度学习**：\n",
      "   - 深度学习是神经网络的一个分支，涉及更复杂的网络结构，如卷积神经网络（CNN）用于图像处理、循环神经网络（RNN）用于处理序列数据、以及长短时记忆网络（LSTM）和变压器模型在自然语言处理中的应用。\n",
      "\n",
      "3. **数据预处理和特征工程**：\n",
      "   - 在机器学习和深度学习中，对数据进行预处理和特征选择是至关重要的。包括数据清理、标准化、正则化等技术。\n",
      "\n",
      "4. **模型评估与优化**：\n",
      "   - 如何评估模型性能，包括使用准确率、精度、召回率、F1分数、ROC-AUC等指标。\n",
      "   - 模型优化技术，如超参数调整和模型调优。\n",
      "\n",
      "5. **概率与统计**：\n",
      "   - 理解概率论和统计学的基本原理，因为许多机器学习算法都是基于这些原理构建的。\n",
      "\n",
      "6. **编程和工具**：\n",
      "   - 深入学习Python编程语言，以及相关的库如NumPy、Pandas、Scikit-learn、TensorFlow和PyTorch等，它们是构建和训练神经网络的常用工具。\n",
      "\n",
      "7. **大数据技术**：\n",
      "   - 学习如何处理和分析大规模数据集，包括使用数据库技术、Hadoop、Spark等。\n",
      "\n",
      "8. **伦理和安全性**：\n",
      "   - 了解机器学习在应用中面临的伦理问题和数据安全性。\n",
      "\n",
      "通过掌握这些领域，你将为自己打下一个坚实的基础，不仅可以更好地理解神经网络，还能够应对机器学习中的复杂问题和应用场景。\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Ronnie\n",
      "\n",
      "告诉我更多关于神经网络的信息\n"
     ]
    }
   ],
   "source": [
    "for m in messages:\n",
    "    m.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "1ec5f6da",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Name: Trump\n",
      "\n",
      "你好啊，我是特朗普\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Ronnie\n",
      "\n",
      "你好\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Name: Ronnie\n",
      "\n",
      "所以你说你在研究神经网络？\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Lance\n",
      "\n",
      "是的，我知道神经网络。但我还应该了解哪些其他东西呢？\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "了解神经网络是掌握机器学习和数据科学的一个重要部分，不过你还可以拓展一些其他相关领域的知识，以便更全面地理解和应用这些技术。这里有几个你可以考虑深入了解的领域和概念：\n",
      "\n",
      "1. **机器学习的基本概念**：\n",
      "   - 监督学习、无监督学习以及强化学习的区别。\n",
      "   - 常见算法，如线性回归、逻辑回归、支持向量机、决策树、随机森林等。\n",
      "\n",
      "2. **深度学习**：\n",
      "   - 深度学习是神经网络的一个分支，涉及更复杂的网络结构，如卷积神经网络（CNN）用于图像处理、循环神经网络（RNN）用于处理序列数据、以及长短时记忆网络（LSTM）和变压器模型在自然语言处理中的应用。\n",
      "\n",
      "3. **数据预处理和特征工程**：\n",
      "   - 在机器学习和深度学习中，对数据进行预处理和特征选择是至关重要的。包括数据清理、标准化、正则化等技术。\n",
      "\n",
      "4. **模型评估与优化**：\n",
      "   - 如何评估模型性能，包括使用准确率、精度、召回率、F1分数、ROC-AUC等指标。\n",
      "   - 模型优化技术，如超参数调整和模型调优。\n",
      "\n",
      "5. **概率与统计**：\n",
      "   - 理解概率论和统计学的基本原理，因为许多机器学习算法都是基于这些原理构建的。\n",
      "\n",
      "6. **编程和工具**：\n",
      "   - 深入学习Python编程语言，以及相关的库如NumPy、Pandas、Scikit-learn、TensorFlow和PyTorch等，它们是构建和训练神经网络的常用工具。\n",
      "\n",
      "7. **大数据技术**：\n",
      "   - 学习如何处理和分析大规模数据集，包括使用数据库技术、Hadoop、Spark等。\n",
      "\n",
      "8. **伦理和安全性**：\n",
      "   - 了解机器学习在应用中面临的伦理问题和数据安全性。\n",
      "\n",
      "通过掌握这些领域，你将为自己打下一个坚实的基础，不仅可以更好地理解神经网络，还能够应对机器学习中的复杂问题和应用场景。\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "Name: Ronnie\n",
      "\n",
      "告诉我更多关于神经网络的信息\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "神经网络是机器学习中的一个重要模型，灵感来源于生物神经系统，特别是大脑的结构和功能。它们特别适用于处理复杂的数据和问题，比如图像识别、语音识别和自然语言处理。以下是关于神经网络的一些关键信息：\n",
      "\n",
      "1. **基础架构**：\n",
      "   - **节点（Neurons）**：类似于大脑中的神经元，节点是神经网络的基本处理单元。每个节点接受输入、进行处理并输出结果。\n",
      "   - **层（Layers）**：神经网络通常由多个层构成，包括输入层、隐藏层和输出层。\n",
      "     - **输入层**：接收输入数据。\n",
      "     - **隐藏层**：进行数据处理和特征提取。这是网络最复杂的一部分，通常包含多个层。\n",
      "     - **输出层**：输出处理后的结果。\n",
      "\n",
      "2. **权重和偏置**：\n",
      "   - 每个连接（连接不同层的节点）都有一个权重。这些权重是神经网络学习的关键，通过训练数据调整以最小化预测误差。\n",
      "   - 偏置是一种额外参数，可帮助模型在无输入时仍能激活。\n",
      "\n",
      "3. **激活函数（Activation Function）**：\n",
      "   - 激活函数决定了节点是否被激活。常见的激活函数包括Sigmoid、ReLU（Rectified Linear Unit）、tanh等。它们引入非线性，使网络能够学习复杂模式。\n",
      "\n",
      "4. **训练神经网络**：\n",
      "   - **反向传播（Backpropagation）**：一种训练算法，用于调整网络中的权重。它通过梯度下降影响权重更新，以减少预测误差。\n",
      "   - **损失函数（Loss Function）**：损失函数衡量预测结果与实际结果的差异，是模型优化的目标。\n",
      "\n",
      "5. **类型**：\n",
      "   - **人工神经网络（ANN）**：最基础的网络类型，通常用于简单的分类或回归任务。\n",
      "   - **卷积神经网络（CNN）**：特别适合处理图像和视频数据，通过卷积层捕获空间特征。\n",
      "   - **循环神经网络（RNN）**：设计用于处理序列数据，如时间序列，适合语音和文本数据。\n",
      "   - **长短时记忆网络（LSTM）**和**门控循环单元（GRU）**：RNN的变体，适合处理具有长期依赖关系的序列数据。\n",
      "\n",
      "6. **应用领域**：\n",
      "   - 神经网络被广泛应用于语音识别、图像识别、自动驾驶、医疗诊断、金融预测以及许多其他领域。\n",
      "\n",
      "神经网络的强大之处在于它们能够自动学习数据的复杂特征并应用于预测任务。然而，它们通常需要大量数据和计算资源进行有效训练。随着技术的发展，神经网络在处理各种复杂任务上的能力不断提高，使其成为现代人工智能的支柱之一。\n"
     ]
    }
   ],
   "source": [
    "# 调用，使用消息过滤\n",
    "output = graph.invoke({'messages': messages})\n",
    "for m in output['messages']:\n",
    "    m.pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce337b91",
   "metadata": {},
   "source": [
    "## 修剪消息\n",
    "\n",
    "另一种方法是根据一定数量的标记修剪信息。<br/>\n",
    "这会将消息历史记录限制为指定数量的标记。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e8bcb3f8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIEAAADqCAIAAAAK8bGeAAAAAXNSR0IArs4c6QAAGPVJREFUeJztnXl8FEXax6u7575zT+47XAlXgglERZBFDrnCIbgKvCzgS0BBQZRlV8XFY0EEQZBwSEAuRY5Iwi1yIyxEDEc2IQkJSSbnZDL31cf+MWzMyiTgdHd6OvT3kz8mXV3Vz/RvurrqqaeqIIIgAAejwEwbwMFp4AVwGjAPpwHzcBowD6cB8/DovgDqwOur7BYjZjGgGAqcDpzuK5JHKIJ5Akgi54nlsDpSTPflIJr6BzYzVpxvLLtprq2wBoSKJHJEouAp/fgOGws0EIjgpjqHxYjy+FBFoSW6hzQmSRrXW07T5WjR4HKutqrEEhguikmShidIKC+/I3HY8Hu3zRX/NlcVWQeM8uvaT0H5JSjW4N/XDKd21aeN9E0Z4kthsd6A2YBeOqzVNzqHvhqk8OVTWDKVGlzIacRx4pmx/hAEUVWmt6Grt/+wsebZjIDoRClVZVKmwbkDDXIfXp9BPpSU5uXkbtH0HewTEkPN65oaDfK21gRHi/oOfiIEcHF4kyamp7RHmpJ8URT0D34+og0MFz5RAgAARs0OuX3ZUFdhI18UWQ3KbppQJ95vaGd7Az8Ok94Mv5SnddrJtrbJanB2f0PvgU/WE9Ca+F6yCz80kiyElAYF55tjkmQyFe2dba8lMV15v9BiaHKSKYSUBmW3zANG+5EpoRPwbIZ/wTk9mRI81+B+kQUCgM9/0r1+EV2lBReayZTg+R28d8tMYT/lMXnnnXcOHz7sQcYhQ4ZoNBoaLAIIDwqNE9//t8XjEjzXQFfniEnqaA0KCws9yFVbW9vcTOqn2j4JfWXVJZ5r4GEfDUOJrHdLMz+L8/jC7XPo0KHdu3dXV1eLRKK+ffsuWrQoKCgoJSXFlSqTyc6cOYNh2ObNm48dO1ZfX69UKgcOHDh//nyxWOx6XCAIioqK2rlz54wZMzZs2ODKO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TkSuQmCC",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from langchain_core.messages import trim_messages\n",
    "\n",
    "# 修建消息后的节点\n",
    "def chat_model_node(state: MessagesState):\n",
    "    messages = trim_messages(\n",
    "            state[\"messages\"],\n",
    "            max_tokens=100,\n",
    "            strategy=\"last\",\n",
    "            token_counter=ChatOpenAI(model=\"gpt-4o\"),\n",
    "            allow_partial=False,\n",
    "        )\n",
    "    return {\"messages\": [llm.invoke(messages)]}\n",
    "\n",
    "# 建立图\n",
    "builder = StateGraph(MessagesState)\n",
    "builder.add_node(\"chat_model\", chat_model_node)\n",
    "builder.add_edge(START, \"chat_model\")\n",
    "builder.add_edge(\"chat_model\", END)\n",
    "graph = builder.compile()\n",
    "\n",
    "display(Image(graph.get_graph().draw_mermaid_png()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "04a0b37f",
   "metadata": {},
   "outputs": [],
   "source": [
    "messages.append(output['messages'][-1])\n",
    "messages.append(HumanMessage(f\"告诉我什么是神经网络\", name=\"Ronnie\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "ea874fba",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='告诉我什么是神经网络', additional_kwargs={}, response_metadata={}, name='Ronnie')]"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trim_messages(\n",
    "            messages,\n",
    "            max_tokens=100,\n",
    "            strategy=\"last\",\n",
    "            token_counter=ChatOpenAI(model=\"gpt-4o\"),\n",
    "            allow_partial=False\n",
    "        )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "0b464ebe",
   "metadata": {},
   "outputs": [],
   "source": [
    "messages_out_trim = graph.invoke({'messages': messages})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2d2f2ad",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.10",
   "language": "python",
   "name": "python310"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
